package com.abhimanyu.bootstrap;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Util {

	public static Date offsetTimeZone(Date date, String fromTZ, String toTZ) {

		// Construct FROM and TO TimeZone instances
		TimeZone fromTimeZone = TimeZone.getTimeZone(fromTZ);
		TimeZone toTimeZone = TimeZone.getTimeZone(toTZ);

		// Get a Calendar instance using the default time zone and locale.
		Calendar calendar = Calendar.getInstance();

		// Set the calendar's time with the given date
		calendar.setTimeZone(fromTimeZone);
		calendar.setTime(date);

		System.out.println("Input: " + calendar.getTime() + " in "
				+ fromTimeZone.getDisplayName());

		// FROM TimeZone to UTC
		calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);

		if (fromTimeZone.inDaylightTime(calendar.getTime())) {
			calendar.add(Calendar.MILLISECOND, calendar.getTimeZone()
					.getDSTSavings() * -1);
		}

		// UTC to TO TimeZone
		calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());

		if (toTimeZone.inDaylightTime(calendar.getTime())) {
			calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
		}

		return calendar.getTime();

	}
}
